﻿using FirstLimitUpMode.Data;
using FirstLimitUpMode.Handles;
using FirstLimitUpMode.Models;
using FirstLimitUpMode.ViewModels;
using GpCommon.CustomControl;
using GpCommon.Helpers;
using GpCommon.Logger;
using GpCommon.Models;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using static GpCommon.Helpers.Win32Helper;

namespace FirstLimitUpMode.Views
{
    /// <summary>
    /// GpDetailView.xaml 的交互逻辑
    /// </summary>
    public partial class GpDetailView : Window
    {
        private SynchronizationContext synContent = null;
        private KeyboardHook _keyboardHook;

        private double Price10;
        private double Price97;
        private float Mark97;
        private string GPCode;
        private double PrePrice;
        private bool IsTopBuy;
        private new string Name;
        private GpDetailView View;
        private DateTime Time = DateTime.Today;

        private bool m_IsTopMode = true;
        public bool IsTopMode
        {
            get { return m_IsTopMode; }
            set
            {
                m_IsTopMode = value;
            }
        }

        private DispatcherTimer timer = new DispatcherTimer();

        private double AcWidth = 360;
        private double AcHeight = 260;

        private int _formula = 0;

        public GpDetailView(string code, float mark97, DateTime time, bool isTopBuy) : this(code, mark97, isTopBuy)
        {
            Time = time;
        }
        public GpDetailView(string code,float mark97, bool isTopBuy)
        {
            InitializeComponent();
            synContent = SynchronizationContext.Current;
            canvasBorder.Width = AcWidth;
            canvasBorder.Height = AcHeight;
            GPCode = code;
            Mark97 = mark97;   // 0.97
            IsTopBuy = isTopBuy;
            CurValueBox.Text = TempData.CurValue.ToString();
            View = this;

            BindImage(_formula);
            _keyboardHook = new KeyboardHook();
            _keyboardHook.SetHook();
            _keyboardHook.SetOnKeyDownEvent(Win32_Keydown);
            _keyboardHook.SetOnKeyUpEvent(Win32_Keyup);
        }

        private void BindImage(int formula)
        {
            string uri = UrlHelper.GetUrlForDayLineImage(GPCode, formula);
            BitmapImage bitImage = new BitmapImage();
            bitImage.BeginInit();
            bitImage.UriSource = new Uri(uri, UriKind.Absolute);
            bitImage.EndInit();
            kLIneImage.Source = bitImage;
        }
        public void ShowView()
        {
            bool isToday = true;
            //if (DateTime.Compare(Time.Date, DateTime.Today) != 0)
            //    isToday = false;
            if (isToday)
            {
                System.Threading.Thread thread = new System.Threading.Thread(() =>
                {
                    Stopwatch stopwatch = new Stopwatch();
                    while (View != null)
                    {
                        stopwatch.Restart();
                        var list = GetData().Result;
                        synContent.Post(FlashViewData, list);

                        var info = GetExData();
                        synContent.Post(FreshExData, info);

                        while (stopwatch.ElapsedMilliseconds < 1000)
                        {
                            Thread.Sleep(500);
                        }
                    }
                });
                thread.IsBackground = true;
                thread.Start();
            }
            //else
            //{
            //    System.Threading.Thread thread = new System.Threading.Thread(() =>
            //    {
            //        var list = GetDataForHistory();
            //        synContent.Post(FlashViewData, list);
            //    });
            //    thread.IsBackground = true;
            //    thread.Start();
            //}

            this.Show();
        }
        private bool IsResponsing = false;
        private void FlashViewData(object obj)
        {
            var list = obj as List<DetailEntity>;
            if (list == null || list.Count == 0) return;
            var curMarkup = list.Last().MarkUp;
            DrawLines(list);
        }
        private void FreshExData(object obj)
        {
            DetailExInfo info = obj as DetailExInfo;
            if (info == null) return;
            HighTextBlock.Text = info.MaxPrice.ToString();
            HighMarkUpTextBlock.Text = info.MaxMarkUp.ToString();
            CurSectorTextBlock.Text = info.Sector;
            SectorRankTextBlock.Text = info.SectorRank;
            VolumeTextBlock.Text = info.Volume.ToString("F2") + "万";
            TurnVolumeTextBlock.Text = info.TurnVolume.ToString("F3") + "亿";
            //var maxMarkup = double.Parse(info.MaxMarkUp);
            //if(maxMarkup >= MainVModel.GetVModelInstance().BuyMarkUp)
            //{
            //    HighTextBlock.Background = new SolidColorBrush(Colors.Red);
            //    HighMarkUpTextBlock.Background = new SolidColorBrush(Colors.Red);
            //}
            //else
            //{
            //    HighTextBlock.Background = new SolidColorBrush(Colors.White);
            //    HighMarkUpTextBlock.Background = new SolidColorBrush(Colors.White);
            //}
            //var strs = info.SectorRank.Split('/');
            //SectorRankTextBlock.Background = new SolidColorBrush(Colors.White);
            //if (strs.Count() == 2 && int.Parse(strs[0]) <= 5)
            //{
            //    SectorRankTextBlock.Background = new SolidColorBrush(Colors.Red);
            //}
        }

        private async Task<List<DetailEntity>> GetData()
        {
            List<DetailEntity> prices = new List<DetailEntity>();
            if (IsResponsing)
                return prices;
            try
            {
                IsResponsing = true;
                //string url = DataHandle.GetUrlForSingleDetailData(GPCode);
                string url = UrlHelper.GetUrlForSingleDetailDataWithPre(GPCode);

                HttpResponseMessage response = await HttpHelper.Client.GetAsync(url).ConfigureAwait(false);
                if (response.IsSuccessStatusCode)
                {
                    response.EnsureSuccessStatusCode();
                    string htmlContent = response.Content.ReadAsStringAsync().Result;
                    if (!string.IsNullOrEmpty(htmlContent))
                    {
                        JObject jobject = JObject.Parse(htmlContent);
                        PrePrice = double.Parse(jobject["data"]["prePrice"].ToString());
                        Name = jobject["data"]["name"].ToString();
                        var trends = jobject["data"]["trends"].Children();
                        int index = 1;
                        foreach (var item in trends)
                        {
                            var strs = item.ToString().Split(',');
                            if (strs.Count() == 8)
                            {
                                DetailEntity ent = new DetailEntity();
                                var datesStr = strs[0].Split(' ');
                                var dates = datesStr[0].Split('-');
                                var times = datesStr[1].Split(':');
                                ent.EntTimeSpan = new DateTime(int.Parse(dates[0]), int.Parse(dates[1]), int.Parse(dates[2]), int.Parse(times[0]), int.Parse(times[1]), 0);
                                ent.Price = double.Parse(strs[2]);
                                ent.MidPrice = double.Parse(strs[7]);
                                double markUp = (ent.Price - PrePrice) / PrePrice * 100.00;
                                ent.MarkUp = Math.Round(markUp, 2, MidpointRounding.AwayFromZero);
                                double midMarkUp = (ent.MidPrice - PrePrice) / PrePrice * 100.00;
                                ent.MidMarkUp = Math.Round(midMarkUp, 2 , MidpointRounding.AwayFromZero);
                                ent.Index = index++;
                                prices.Add(ent);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
                IsResponsing = false;
                Logger.Error(ex);
            }
            IsResponsing = false;
            return prices;
        }

        private DetailExInfo GetExData()
        {
            try
            {
                List<SectorEntity> sectors = GpNetDataHelper.GetSectorRank().Result;
                var curSecotrId = GpNetDataHelper.GetGpSector(GPCode).Result;
                var curEnt = GpNetDataHelper.GetGpCurInfoByCode(GPCode).Result;
                if (sectors == null || sectors.Count == 0 || string.IsNullOrEmpty(curSecotrId) || curEnt == null)
                    return null;
                DetailExInfo exInfo = new DetailExInfo();
                exInfo.MaxPrice = curEnt.HighPrice.ToString("F2");
                exInfo.MaxMarkUp = ((curEnt.HighPrice - curEnt.YesClsPrice) / curEnt.YesClsPrice * 100.0).ToString("F2");
                var index = sectors.FindIndex(x => x.SectorId == curSecotrId);
                if(index >= 0)
                {
                    exInfo.Sector = sectors[index].SectorName;
                    exInfo.SectorRank = (index + 1) + "/"  + sectors.Count;
                }
                exInfo.Volume = curEnt.Volume;
                exInfo.TurnVolume = curEnt.TurnVolume;
                return exInfo;
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
            return null;
        }

        //private List<DetailEntity> GetDataForHistory()
        //{
        //    List<DetailEntity> ents = new List<DetailEntity>();
        //    var dayInfos = AlGpHelper.GetLocalHistoryDayInfoByCode(Time.Year, GPCode);
        //    int dayIndex = dayInfos.FindIndex(x => x.Time == Time);
        //    if (dayIndex <= 0)
        //        return ents;
        //    PrePrice = dayInfos[dayIndex - 1].ClsPrice;
        //    var gps = AlGpHelper.GetValidGps();
        //    Name = gps.Find(x => x.Item1 == GPCode).Item2;
        //    var msEnts = AlGpHelper.GetDayMS_OLEntityByCode(Time, GPCode).Result;
        //    for (int i = 0; i < msEnts.Count; i++)
        //    {
        //        DetailEntity ent = new DetailEntity();
        //        ent.EntTimeSpan = msEnts[i].Time;
        //        ent.Price = msEnts[i].Price;
        //        ent.MidPrice = msEnts[i].MidPrice;
        //        double markUp = (ent.Price - PrePrice) / PrePrice * 100.00;
        //        ent.MarkUp = Math.Round(markUp, 2);
        //        double midMarkUp = (ent.MidPrice - PrePrice) / PrePrice * 100.00;
        //        ent.MidMarkUp = Math.Round(midMarkUp, 2);
        //        ent.Index = i + 1;
        //        ents.Add(ent);
        //    }
        //    return ents;
        //}
        private List<int> _removePreMinute = new List<int> {25,26,27,28,29 };
        private void DrawLines(List<DetailEntity> entities)
        {
            canvas.Children.Clear();

            // 计算折线图的最大值和最小值
            double maxValue = entities.Select(x => x.MarkUp).Max();
            double minValue = entities.Select(x => x.MarkUp).Min();
            var curMarkup = entities.Last().MarkUp;
            var curPrice = entities.Last().Price.ToString("F2");

            List< DetailEntity > preEntities = new List<DetailEntity >();
            for (int i = 0; i < entities.Count; i++)
            {
                if (entities[i].EntTimeSpan.Hour == 9 && entities[i].EntTimeSpan.Minute < 25)
                {
                    preEntities.Add(entities[i]);
                    entities.RemoveAt(i--);
                    continue;
                }
                if(entities[i].EntTimeSpan.Hour == 9 && _removePreMinute.Contains(entities[i].EntTimeSpan.Minute))
                {
                    entities.RemoveAt(i--);
                    continue;
                }
            }

            if (entities.Count <= 0)
                return;



            if (Math.Abs(maxValue) >= Math.Abs(minValue))
            {
                maxValue = Math.Abs(maxValue);
                minValue = -maxValue;
            }
            else
            {
                maxValue = Math.Abs(minValue);
                minValue = -maxValue;
            }

            if (IsTopMode)
            {
                double topOffset = Math.Round(PrePrice * 0.1, 2, MidpointRounding.AwayFromZero);
                maxValue = Math.Round(topOffset / PrePrice * 100, 2 , MidpointRounding.AwayFromZero);
                minValue = -maxValue;
            }
            double preWidth = 45;
            // 计算折线图数据点的间距
            double dataPointWidth = (AcWidth - preWidth) / 241;

            /// 平盘线
            Line dotedline = new Line
            {
                X1 = 0,
                Y1 = AcHeight / 2,
                X2 = AcWidth,
                Y2 = AcHeight / 2,
                Stroke = Brushes.Gray,
                StrokeThickness = 1.5,
                StrokeDashArray = new DoubleCollection(new List<double> { 3, 1 })
            };
            canvas.Children.Add(dotedline);

            /// 1点上线
            Line pct1Line = new Line
            {
                X1 = 0,
                Y1 = AcHeight - (1 - minValue) / (maxValue - minValue) * AcHeight,
                X2 = AcWidth,
                Y2 = AcHeight - (1 - minValue) / (maxValue - minValue) * AcHeight,
                Stroke = Brushes.LightBlue,
                StrokeThickness = 1.5,
                StrokeDashArray = new DoubleCollection(new List<double> { 2, 2 })
            };
            canvas.Children.Add(pct1Line);
            /// 1点下线
            Line pct2Line = new Line
            {
                X1 = 0,
                Y1 = AcHeight - (-1 - minValue) / (maxValue - minValue) * AcHeight,
                X2 = AcWidth,
                Y2 = AcHeight - (-1 - minValue) / (maxValue - minValue) * AcHeight,
                Stroke = Brushes.LightBlue,
                StrokeThickness = 1.5,
                StrokeDashArray = new DoubleCollection(new List<double> { 2, 2 })
            };
            canvas.Children.Add(pct2Line);

            // 97线
            Line line97 = new Line
            {
                X1 = 0,
                Y1 = AcHeight - (Mark97 - minValue) / (maxValue - minValue) * AcHeight,
                X2 = AcWidth,
                Y2 = AcHeight - (Mark97 - minValue) / (maxValue - minValue) * AcHeight,
                Stroke = Brushes.LightBlue,
                StrokeThickness = 1.5,
                StrokeDashArray = new DoubleCollection(new List<double> { 2, 2 })
            };
            canvas.Children.Add(line97);

            // 绘制盘前线
            for (int i = 0; i < preEntities.Count - 1; i++)
            {
                double x1 = i * 5;
                double y1 = AcHeight - (preEntities[i].MarkUp - minValue) / (maxValue - minValue) * AcHeight;

                double x2 = (i + 1) * 5;
                double y2 = AcHeight - (preEntities[i + 1].MarkUp - minValue) / (maxValue - minValue) * AcHeight;

                Line line = new Line
                {
                    X1 = x1,
                    Y1 = y1,
                    X2 = x2,
                    Y2 = y2,
                    Stroke = Brushes.DarkSlateGray,
                    StrokeThickness = 1.5
                };

                canvas.Children.Add(line);
            }
            // 绘制盘前分割线
            Line lineSplit = new Line
            {
                X1 = preWidth,
                Y1 = AcHeight,
                X2 = preWidth,
                Y2 = 0,
                Stroke = Brushes.LightGray,
                StrokeThickness = 1.5
            };

            canvas.Children.Add(lineSplit);

            // 绘制折线
            for (int i = 0; i < entities.Count - 1; i++)
            {
                double x1 = i * dataPointWidth + preWidth;
                double y1 = AcHeight - (entities[i].MarkUp - minValue) / (maxValue - minValue) * AcHeight;

                double x2 = (i + 1) * dataPointWidth + preWidth;
                double y2 = AcHeight - (entities[i + 1].MarkUp - minValue) / (maxValue - minValue) * AcHeight;

                double y3 = AcHeight - (entities[i].MidMarkUp - minValue) / (maxValue - minValue) * AcHeight;
                double y4 = AcHeight - (entities[i + 1].MidMarkUp - minValue) / (maxValue - minValue) * AcHeight;

                Line line = new Line
                {
                    X1 = x1,
                    Y1 = y1,
                    X2 = x2,
                    Y2 = y2,
                    Stroke = Brushes.DarkSlateGray,
                    StrokeThickness = 1.5
                };
                Line lineMid = new Line
                {
                    X1 = x1,
                    Y1 = y3,
                    X2 = x2,
                    Y2 = y4,
                    Stroke = Brushes.Orange,
                    StrokeThickness = 1.5
                };


                canvas.Children.Add(line);
                canvas.Children.Add(lineMid);
            }


            Label maxMarkLabel = new Label();
            maxMarkLabel.Content = maxValue + "%";
            canvas.Children.Add(maxMarkLabel);
            Canvas.SetLeft(maxMarkLabel, AcWidth - 50);
            Canvas.SetTop(maxMarkLabel, 0);

            Label minMarkLabel = new Label();
            minMarkLabel.Content = minValue + "%";
            canvas.Children.Add(minMarkLabel);
            Canvas.SetLeft(minMarkLabel, AcWidth - 50);
            Canvas.SetTop(minMarkLabel, AcHeight - 25);

            Label maxPriceLabel = new Label();
            Price10 = (PrePrice * (1 + maxValue / 100.0));
            maxPriceLabel.Content = Price10.ToString("F2");
            canvas.Children.Add(maxPriceLabel);
            Canvas.SetLeft(maxPriceLabel, 0);
            Canvas.SetTop(maxPriceLabel, 0);

            Label minPriceLabel = new Label();
            minPriceLabel.Content = (PrePrice * (1 + minValue / 100.0)).ToString("F2");
            canvas.Children.Add(minPriceLabel);
            Canvas.SetLeft(minPriceLabel, 0);
            Canvas.SetTop(minPriceLabel, AcHeight - 25);

            Label midPriceLabel = new Label();
            midPriceLabel.Content = (PrePrice).ToString("F2");
            canvas.Children.Add(midPriceLabel);
            Canvas.SetLeft(midPriceLabel, 0);
            Canvas.SetTop(midPriceLabel, AcHeight / 2);

            Label m97Label = new Label();
            //Price97 = PrePrice * (1 + maxValue / 100.0 * Mark97 / 10);
            Price97 = CommonUtility.RoundUp(PrePrice * (1 + Mark97 / 100.0),2);
            m97Label.Content = Price97.ToString();
            m97Label.Foreground = new SolidColorBrush(Colors.Blue);
            canvas.Children.Add(m97Label);
            Canvas.SetLeft(m97Label, 0 - 50);
            Canvas.SetTop(m97Label, 0);

            // 标题 当前价格 当前涨幅
            
            Label titleLabel = new Label();
            titleLabel.Content = Name + "(" + GPCode + ")";
            titleLabel.FontSize = 15;
            titleLabel.FontWeight = FontWeights.Bold;
            canvas.Children.Add(titleLabel);
            Canvas.SetLeft(titleLabel, AcWidth / 2 - 80);
            Canvas.SetTop(titleLabel, 0 - 35);

            Label priceLabel = new Label();
            priceLabel.Content = curPrice;
            priceLabel.FontSize = 13;
            priceLabel.FontWeight = FontWeights.Bold;
            canvas.Children.Add(priceLabel);
            Canvas.SetLeft(priceLabel, 0 - 30);
            Canvas.SetTop(priceLabel, 0 - 20);

            Label markupLabel = new Label();
            markupLabel.Content = curMarkup.ToString() + "%";
            markupLabel.FontSize = 13;
            markupLabel.FontWeight = FontWeights.Bold;
            canvas.Children.Add(markupLabel);
            Canvas.SetLeft(markupLabel, AcWidth - 30);
            Canvas.SetTop(markupLabel, 0 - 20);

            if (curMarkup > 0)
            {
                priceLabel.Foreground = new SolidColorBrush(Colors.Red);
                markupLabel.Foreground = new SolidColorBrush(Colors.Red);
            }
            else if (curMarkup < 0)
            {
                priceLabel.Foreground = new SolidColorBrush(Colors.Green);
                markupLabel.Foreground = new SolidColorBrush(Colors.Green);
            }
            else
            {
                priceLabel.Foreground = new SolidColorBrush(Colors.Black);
                markupLabel.Foreground = new SolidColorBrush(Colors.Black);
            }

            if (m_Line != null)
            {
                canvas.Children.Remove(m_Line);
                canvas.Children.Add(m_Line);
            }
        }

        private void canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            IsTopMode = !IsTopMode;
        }

        private Line m_Line;
        private void canvas_MouseMove(object sender, MouseEventArgs e)
        {
            var pos = e.GetPosition(this);
            // 计算折线图数据点的间距
            double dataPointWidth = AcWidth / 241;
            int indexX = (int)(pos.X / dataPointWidth);

            if (m_Line == null)
            {
                m_Line = new Line
                {
                    X1 = indexX * dataPointWidth - 50,
                    Y1 = 0,
                    X2 = indexX * dataPointWidth - 50,
                    Y2 = AcHeight,
                    Stroke = Brushes.LightBlue,
                    StrokeThickness = 1.5
                };
            }
            else
            {
                m_Line.X1 = indexX * dataPointWidth - 50;
                m_Line.X2 = indexX * dataPointWidth - 50;
            }
            canvas.Children.Remove(m_Line);
            canvas.Children.Add(m_Line);
        }

        private void canvas_MouseLeftButtonUp_1(object sender, MouseButtonEventArgs e)
        {
            var pos = e.GetPosition(this);
            // 计算折线图数据点的间距
            double dataPointWidth = AcWidth / 241;
            int indexX = (int)(pos.X / dataPointWidth);

            if (m_Line == null)
            {
                m_Line = new Line
                {
                    X1 = indexX * dataPointWidth - 50,
                    Y1 = 0,
                    X2 = indexX * dataPointWidth - 50,
                    Y2 = AcHeight,
                    Stroke = Brushes.LightBlue,
                    StrokeThickness = 1.5
                };
            }
            else
            {
                m_Line.X1 = indexX * dataPointWidth - 50;
                m_Line.X2 = indexX * dataPointWidth - 50;
            }
            canvas.Children.Remove(m_Line);
            canvas.Children.Add(m_Line);
        }

        private void addBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!TempData.LockList.Contains(GPCode))
            {
                TempData.LockList.Add(GPCode);
                TempData.WriteLockGps();

                //MessageView.Create(Name + "(" + GPCode + ")添加到自选");
            }
        }

        private void closeBtn_Click(object sender, RoutedEventArgs e)
        {
            //timer.Stop();
            View = null;
            this.Close();
        }

        private void removeBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!TempData.RemoveList.Contains(GPCode))
            {
                TempData.RemoveList.Add(GPCode);

                //MessageView.Create(Name + "(" + GPCode + ")被删除");
            }
            closeBtn_Click(sender, e);
        }

        private void changeModeBtn_Click(object sender, RoutedEventArgs e)
        {
            IsTopMode = !IsTopMode;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            View = null;
            int.TryParse(CurValueBox.Text, out TempData.CurValue);
            _keyboardHook.UnHook();
        }
        private void aremoveLocktn_Click(object sender, RoutedEventArgs e)
        {
            if (TempData.LockList.Contains(GPCode))
            {
                TempData.LockList.Remove(GPCode);
                TempData.WriteLockGps();

                //MessageView.Create(Name + "(" + GPCode + ")移出自选");
            }
            closeBtn_Click(sender, e);
        }

        //private void AutoPayBtn_Click(object sender, RoutedEventArgs e)
        //{
        //    if (!TempData.PlaceOrderList.Contains(GPCode))
        //        TempData.PlaceOrderList.Add(GPCode);

        //    //var pts = LocationCheckView.GetLocations();
        //    //while (pts.Count != LocationCheckView.MaxNum)
        //    //{
        //    //    if (MessageBox.Show("是否要先检查定位信息？", "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
        //    //    {
        //    //        LocationCheckView locationCheckView = new LocationCheckView();
        //    //        locationCheckView.ShowDialog();
        //    //        pts = LocationCheckView.GetLocations();
        //    //    }
        //    //    else
        //    //    {
        //    //        return;
        //    //    }
        //    //}

        //    try
        //    {
        //        IntPtr mainIntptr = Win32Helper.FindWindow(null, "网上股票交易系统5.0");
        //        if (mainIntptr != IntPtr.Zero)
        //        {
        //            AutomationElement rootAE = AutomationElement.FromHandle(mainIntptr);

        //            UIAutomationHelper.InvokeExpandCollapseAE(rootAE, AutomationElement.NameProperty, "智能交易");
        //            UIAutomationHelper.InvokeExpandCollapseAE(rootAE, AutomationElement.NameProperty, "条件下单");
        //            UIAutomationHelper.InvokeSelectionItemAE(rootAE, AutomationElement.NameProperty, "定价买入");

        //            // 代号
        //            var codePt = UIAutomationHelper.GetMidPosition(rootAE, AutomationElement.AutomationIdProperty, "1032");
        //            MouseFlag.MouseLeftDoubleClickEvent((int)codePt.X, (int)codePt.Y, 0);

        //            foreach (var item in GPCode)
        //            {
        //                KeyBoard.keyPress(KeyPressByteConvert(item));
        //            }

        //            //触发价格
        //            var executePt = UIAutomationHelper.GetMidPosition(rootAE, AutomationElement.AutomationIdProperty, "1070");

        //            MouseFlag.MouseLeftDoubleClickEvent((int)executePt.X, (int)executePt.Y, 0);
        //            var str97 = Price97.ToString("F2");
        //            foreach (var item in str97)
        //            {
        //                KeyBoard.keyPress(KeyPressByteConvert(item));
        //            }

        //            // 五档定价
        //            //var subAEs = rootAE.FindAll(TreeScope.Subtree, new PropertyCondition(AutomationElement.NameProperty, "即时卖一价"));
        //            //AutomationElement subAE = null;
        //            //foreach (AutomationElement item in subAEs)
        //            //{
        //            //    if (item.Current.ControlType == ControlType.ListItem)
        //            //    {
        //            //        subAE = item;
        //            //        break;
        //            //    }
        //            //}
        //            //var selectPt = (SelectionItemPattern)subAE.GetCurrentPattern(SelectionItemPattern.Pattern);
        //            //selectPt.Select();

        //            // 自定义定价
        //            UIAutomationHelper.InvokeInvokeAE(rootAE, AutomationElement.AutomationIdProperty, "3610"); // 自定义

        //            // 委托价
        //            var buyInPt = UIAutomationHelper.GetMidPosition(rootAE, AutomationElement.AutomationIdProperty, "1068");
        //            MouseFlag.MouseLeftDoubleClickEvent((int)buyInPt.X, (int)buyInPt.Y, 0);
        //            foreach (var item in Price10)
        //            {
        //                KeyBoard.keyPress(KeyPressByteConvert(item));
        //            }


        //            //数量

        //            var numPt = UIAutomationHelper.GetMidPosition(rootAE, AutomationElement.AutomationIdProperty, "1069");

        //            MouseFlag.MouseLeftDoubleClickEvent((int)numPt.X, (int)numPt.Y, 0);
        //            if (int.TryParse(CurValueBox.Text, out int tempValue))
        //            {
        //                var count = (int)(tempValue / 100 / Price97) * 100;
        //                foreach (var item in count.ToString())
        //                {
        //                    KeyBoard.keyPress(KeyPressByteConvert(item));
        //                }
        //            }

        //            UIAutomationHelper.InvokeInvokeAE(rootAE, AutomationElement.AutomationIdProperty, "3551"); // 勾选协议
        //            Thread.Sleep(100);
        //            UIAutomationHelper.InvokeInvokeAE(rootAE, AutomationElement.AutomationIdProperty, "1006"); // 创建
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message);
        //    }
        //}
        private const int EM_REPLACESEL = 0x00C2;
        private const int BM_SETCHECK = 0x00F1;
        private const int BST_CHECKED = 0x0001;
        private void AutoPayBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!TempData.OrderToBuyList.Contains(GPCode))
                TempData.OrderToBuyList.Add(GPCode);
            if (int.TryParse(CurValueBox.Text, out int tempValue))
            {
                var count = (int)(tempValue / 100 / Price97) * 100;
                if (IsTopBuy)
                {
                    double tempBuyPrice = Price10 - 0.01;  // 
                    count = (int)(tempValue / 100 / tempBuyPrice) * 100;
                    AutoHelper.BuyExecute(GPCode, Price10 - 0.01, Price10, count);
                }
                else
                {
                    AutoHelper.BuyExecute(GPCode, Price97, Price10, count);
                }
            }
        }

        private static List<IntPtr> FindChildControls(IntPtr hWndParent, string className, string windowName = null)
        {
            List<IntPtr> handles = new List<IntPtr>();
            IntPtr hWndChildAfter = IntPtr.Zero;

            while (true)
            {
                IntPtr childHandle = Win32Helper.FindWindowEx(hWndParent, hWndChildAfter, className, windowName);
                if (childHandle == IntPtr.Zero)
                    break;
                handles.Add(childHandle);
                hWndChildAfter = childHandle;
            }
            return handles;
        }
        private byte KeyPressByteConvert(char c)
        {
            switch (c)
            {
                case '0':
                    return KeyBoard.vKey0;
                case '1':
                    return KeyBoard.vKey1;
                case '2':
                    return KeyBoard.vKey2;
                case '3':
                    return KeyBoard.vKey3;
                case '4':
                    return KeyBoard.vKey4;
                case '5':
                    return KeyBoard.vKey5;
                case '6':
                    return KeyBoard.vKey6;
                case '7':
                    return KeyBoard.vKey7;
                case '8':
                    return KeyBoard.vKey8;
                case '9':
                    return KeyBoard.vKey9;
                case '.':
                    return KeyBoard.vKeyDecimal;
            }
            return KeyBoard.vKey0;
        }

        #region 全局键盘
        private Key _lastKey = Key.None;

        private void Win32_Keydown(Key key)
        {
            if (key == Key.LeftAlt)
            {
                _lastKey = key;
            }
            else if (_lastKey == Key.LeftAlt && key == Key.A)
            {
                if (this.Visibility == Visibility.Visible)
                {
                    this.Visibility = Visibility.Hidden;
                }
                else
                {
                    this.Visibility = Visibility.Visible;
                }
            }
            else
            {
                _lastKey = Key.None;
            }
        }
        private void Win32_Keyup(Key key)
        {
            if (key == Key.LeftAlt)
            {
                _lastKey = Key.None;
            }
        }



        #endregion

        private bool isShowKLine = true;
        private void showKLineBtn_Click(object sender, RoutedEventArgs e)
        {
            if (isShowKLine)
            {
                kLineCol.Width = new GridLength(0);
                this.Width = 480;
                isShowKLine = false;
            }
            else
            {
                kLineCol.Width = new GridLength(800);
                this.Width = 1160;
                isShowKLine = true;
            }
        }

        private void kLIneImage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (_formula == 0)
                _formula = 1;
            else
                _formula = 0;
            BindImage(_formula);
        }
    }

}
